import React, { PureComponent } from "react";
import { Card, Divider, Popconfirm } from "antd";
import { connect } from "dva";
import { openNotificationWithIcon, goToUrl } from "utils/comm";
import styles from "./index.less";
import TableList from "../../../components/tablelist/TableList";
import QueryExtra from "./components/QueryExtra";
import PageLayout from "../../../components/pageconlayout/PageLayout";
import CardTitle from "./components/CardTitle";
import CreateForm from "./components/CreateForm";
import UserAdd from "./components/UserAdd";
import {
  getMenuRouter,
  getPageOperate,
} from "../../../components/layouts/menuFn";

const emptyParams = {
  searchName: "",
};

@connect(({ tenantManagement, loading, Public }) => ({
  tenantManagementStore: tenantManagement,
  loading,
  menuDataList: Public.menuDataList,
  resourceList: Public.resourceList,
}))
class TenantManagement extends PureComponent {
  state = {
    visible: false,
    page: {
      pageNum: 1,
      pageSize: 6,
    },
  };

  getMenuRouter = getMenuRouter.bind(this);

  getPageOperate = getPageOperate.bind(this);

  searchParams = emptyParams;

  constructor(props) {
    super(props);
    this.openNotificationWithIcon = openNotificationWithIcon.bind(this);
  }

  componentDidMount() {
    this.isLeaf = false;
    this.initData();
  }

  componentWillUnmount() {
    this.isLeaf = true;
    const { dispatch } = this.props;
    dispatch({ type: "tenantManagement/clearData" });
  }

  getOprateDisable = (type) => {
    const {
      location: { pathname = "" },
      menuDataList,
      resourceList,
    } = this.props;
    const res = this.getPageOperate(type, pathname, menuDataList, resourceList);
    return res;
  };

  getColumns = () => {
    const columns = [
      {
        title: "租户名称",
        dataIndex: "tenantName",
        key: "tenantName",
      },
      {
        title: "租户编码",
        dataIndex: "tenantCode",
        key: "tenantCode",
        hiddenTooltip: true,
      },
      {
        title: "联系人",
        dataIndex: "contactName",
        key: "contactName",
        hiddenTooltip: true,
      },
      {
        title: "联系电话",
        dataIndex: "contactPhone",
        key: "contactPhone",
        hiddenTooltip: true,
      },
      {
        title: "创建时间",
        dataIndex: "createTime",
        key: "createTime",
        width: "25%",
      },
      {
        title: "租户描述",
        dataIndex: "description",
        key: "description",
      },
      {
        title: "操作",
        dataIndex: "opration",
        render: (text, record) => {
          const del = this.getOprateDisable("delete");
          const edit = this.getOprateDisable("edit");
          return (
            <div>
              {edit && (
                <a
                  onClick={(e) => {
                    e.preventDefault();
                    this.handleCreateVisible(true, record);
                  }}
                >
                  编辑
                </a>
              )}
              {del && edit && <Divider type="vertical" />}
              {del && (
                <Popconfirm
                  placement="left"
                  title={`确定删除租户：${record.tenantName}?`}
                  onConfirm={() => {
                    this.handleDel(record);
                  }}
                  okText="确定"
                  cancelText="取消"
                >
                  <a
                    onClick={(e) => {
                      e.preventDefault();
                    }}
                  >
                    删除
                  </a>
                </Popconfirm>
              )}
              <Divider type="vertical" />
              <a
                onClick={(e) => {
                  e.preventDefault();
                  this.handleUser(true, record);
                }}
              >
                用户管理
              </a>
              <Divider type="vertical" />
              <a
                onClick={(e) => {
                  e.preventDefault();
                  this.handleApp(record);
                }}
              >
                应用管理
              </a>
            </div>
          );
        },
      },
    ];
    return columns;
  };

  getFormThis = (formThis, type = "advancedFilter") => {
    if (type === "queryExtra") {
      this.queryExtraForm = formThis;
    }
  };

  // 获取查询参数
  getQueryParam = () => {
    const {
      page: { pageNum, pageSize },
    } = this.state;
    return { ...this.searchParams, pageNum, pageSize };
  };

  // 触发查询
  initData = () => {
    const { dispatch } = this.props;
    const params = this.getQueryParam();
    dispatch({ type: "tenantManagement/getTenantList", payload: params });
  };

  // 页码页数改变
  handlePageChange = (pageNum, pageSize) => {
    this.setState({ page: { pageNum, pageSize } }, () => {
      this.initData();
    });
  };

  // 搜索
  handleSearch = () => {
    const { page } = this.state;
    if (this.queryExtraForm) this.queryExtraForm.handleSubmit();
    this.setState({ page: { ...page, pageNum: 1 } }, () => {
      this.initData();
    });
  };

  // 查询参数改变
  handleParamsChange = (newparams) => {
    this.searchParams = { ...this.searchParams, ...newparams };
  };

  // 创建租户
  handleCreateVisible = (visible, record = "", isQuery = false) => {
    this.record = record;
    this.title = "新增租户";
    if (record) this.title = "编辑租户";
    if (this.isLeaf) return;
    this.setState({ visible });
    if (isQuery) {
      this.handleSearch();
    }
  };

  // 用户管理弹窗
  handleUser = (visible, record = "") => {
    this.record = record;
    const { id } = record;
    this.title = "用户管理";
    this.setState({ userVisible: visible, id });
  };

  // 跳转应用管理页面
  handleApp = (record = "") => {
    const { dispatch } = this.props;
    const { id } = record;
    // 页面跳转至应用管理页面，
    goToUrl(
      `/basicdata/app&businessmanagement?tenantId=${id}`,
      "app&businessmanagement",
      "basicdata",
      dispatch,
    );
    // 并且应用管理左侧树，选中对应租户信息
  };

  // 删除租户
  handleDel = (record = {}) => {
    if (!record.id) return;
    const { dispatch } = this.props;
    dispatch({
      type: "tenantManagement/delTenant",
      payload: { tenantId: record.id },
    }).then(({ errCode, errMsg }) => {
      if (errCode === 0) {
        this.handleSearch();
      } else {
        this.openNotificationWithIcon("warning", "", errMsg || "操作失败");
      }
    });
  };

  render() {
    const { tenantManagementStore, loading, dispatch } = this.props;
    const {
      page: { pageNum, pageSize },
      visible,
      userVisible,
      id,
    } = this.state;
    const { tenantList = [], totalCount = 0 } = tenantManagementStore;
    const listLoading = loading.effects["tenantManagement/getTenantList"];
    const createLoading = loading.effects["tenantManagement/addTenant"];
    const editLoading = loading.effects["tenantManagement/editTenant"];
    // TODO 提交授权用户loading
    const modalLoading =
      loading.effects["tenantManagement/submitUsers"] || false;

    return (
      <div className={styles.root}>
        <PageLayout
          leftContent={null}
          rightContent={
            <Card
              title={
                <CardTitle
                  total={totalCount}
                  handleCreateVisible={this.handleCreateVisible}
                  addVisible={this.getOprateDisable("add")}
                />
              }
              extra={
                <QueryExtra
                  handleParamsChange={this.handleParamsChange}
                  onSearch={this.handleSearch}
                  getFormThis={this.getFormThis}
                />
              }
              bodyStyle={{
                minHeight: window.innerHeight - 64 - 16 - 16 - 48 - 104,
              }}
              style={{ width: "100%" }}
            >
              <TableList
                dataSource={tenantList}
                loading={listLoading}
                columns={this.getColumns()}
                titleName="tenantName"
                operationName="opration"
                onPageChange={this.handlePageChange}
                rowKey="id"
                className={styles.listcon}
                pagination={{
                  showQuickJumper: true,
                  showSizeChanger: true,
                  pageSizeOptions: ["6", "10", "20", "30"],
                  current: pageNum,
                  pageSize,
                  total: totalCount,
                }}
              />
            </Card>
          }
        />
        {visible && (
          <CreateForm
            title={this.title}
            visible={visible}
            data={this.record}
            handleCreateVisible={this.handleCreateVisible}
            dispatch={dispatch}
            confirmLoading={createLoading || editLoading}
          />
        )}
        {userVisible && (
          <UserAdd
            visible={userVisible}
            handleCancel={this.handleUser}
            dispatch={dispatch}
            id={id}
            confirmLoading={modalLoading}
          />
        )}
      </div>
    );
  }
}

export default TenantManagement;
